import time
import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import fpgrowth, apriori, association_rules


#使用mlxtend提供的算法对apriori与fp树结果进行对比
start_time = time.time()
for i in range(10):
    # 读取CSV文件
    df = pd.read_csv("D:\\Lenovo\\Desktop\\云南大学\\空间数据挖掘\\实验数据\\实验数据5.csv", header=None)
    pre_transactions = df.values.tolist()
    transactions = [[x for x in subset if pd.isnull(x) == False] for subset in pre_transactions]

    # 使用TransactionEncoder将交易记录转换为适合FP-Growth和Apriori算法的格式
    te = TransactionEncoder()
    te_ary = te.fit(transactions).transform(transactions)
    df = pd.DataFrame(te_ary, columns=te.columns_)

    # 使用FP-Growth算法生成频繁项集
    frequent_itemsets_fpgrowth = fpgrowth(df, min_support=0.2, use_colnames=True)
    # 使用Apriori算法生成频繁项集
    frequent_itemsets_apriori = apriori(df, min_support=0.2, use_colnames=True)


    # 生成关联规则
    rules_fpgrowth = association_rules(frequent_itemsets_fpgrowth, metric="confidence", min_threshold=0.7)
    rules_apriori = association_rules(frequent_itemsets_apriori, metric="confidence", min_threshold=0.7)

    # 按置信度降序排序
    rules_fpgrowth = rules_fpgrowth.sort_values(by='confidence', ascending=False)
    rules_apriori = rules_apriori.sort_values(by='confidence', ascending=False)

end_time = time.time()
print("运行时间：", (end_time - start_time)/10, "秒")

with open("apriori_fptree.txt",'w') as f:
    f.write("FP-Growth关联规则及其置信度：\n")
    f.write(str(rules_fpgrowth[['antecedents', 'consequents', 'support', 'confidence', 'lift']]))
    f.write("\nApriori关联规则及其置信度：\n")
    f.write(str(rules_apriori[['antecedents', 'consequents', 'support', 'confidence', 'lift']]))
    f.write(str(frequent_itemsets_fpgrowth))
    f.write('FP-Growth频繁项集及支持度：\n')
    f.write('\nApriori频繁项集及支持度：\n')
    f.write(str(frequent_itemsets_apriori))

